package com.pan.kang.util;

import java.util.Arrays;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;

public class BooleanUtils<T> {

    private final boolean result;

    public BooleanUtils(boolean result) {
        this.result = result;
    }

    public static <T> BooleanUtils<T> isAnyMatch(Boolean... booleans) {
        boolean result = Arrays.stream(booleans).filter(Objects::nonNull).anyMatch(Boolean::booleanValue);
        return new BooleanUtils<>(result);
    }

    public static <T> BooleanUtils<T> isAllMatch(Boolean... booleans) {
        boolean result = Arrays.stream(booleans).filter(Objects::nonNull).allMatch(Boolean::booleanValue);
        return new BooleanUtils<>(result);
    }

    public static <T> BooleanUtils<T> isAllMatch(BooleanSupplier... booleanSuppliers) {
        boolean result = Arrays.stream(booleanSuppliers).filter(Objects::nonNull)
                .allMatch(BooleanSupplier::getAsBoolean);
        return new BooleanUtils<>(result);
    }

    public static <T> BooleanUtils<T> isAnyMatch(BooleanSupplier... booleanSuppliers) {
        boolean result = Arrays.stream(booleanSuppliers).filter(Objects::nonNull)
                .anyMatch(BooleanSupplier::getAsBoolean);
        return new BooleanUtils<>(result);
    }

    // 带返回值的if-else
    public T handleConditionWithReturn(Supplier<T> ifSupplier, Supplier<T> elseSupplier) {
        if (this.result && null != ifSupplier) {
            return ifSupplier.get();
        }
        if (null == elseSupplier) {
            return null;
        }
        return elseSupplier.get();
    }

    // 带返回值的if
    public T handleConditionWithReturn(Supplier<T> ifSupplier) {
        if (this.result && null != ifSupplier) {
            return ifSupplier.get();
        }
        return null;
    }

    // 不带返回值的if-else
    public void handleCondition(Runnable ifRunnable, Runnable elseRunnable) {
        if (this.result && null != ifRunnable) {
            ifRunnable.run();
            return;
        }
        if (null == elseRunnable) {
            return;
        }
        elseRunnable.run();
    }

    // 不带返回值的if
    public void handleCondition(Runnable ifRunnable) {
        if (this.result && null != ifRunnable) {
            ifRunnable.run();
        }
    }

}

